package com.oa.code;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;

import javax.imageio.stream.FileImageOutputStream;

import org.jbarcode.JBarcode;
import org.jbarcode.encode.BarcodeEncoder;
import org.jbarcode.encode.Code39Encoder;
import org.jbarcode.paint.BaseLineTextPainter;
import org.jbarcode.paint.EAN13TextPainter;
import org.jbarcode.paint.WideRatioCodedPainter;
import org.jbarcode.paint.WidthCodedPainter;
import org.jbarcode.util.ImageUtil;

public class TestSingleImage {

	public static void main(String[] args) {
		try {
			byte[] by = createDimensionalCode("1234567893243213454");
			// ���ɵ�ͼƬ�߶��ǹ̶�60����
			String path = "D:\\12w3.jpg";// ���gif��jpg��png��bmp����
			// ��������
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
			// ��byte����д�뱾��Ӳ��
			imageOutput.write(by, 0, by.length);
			// �ر�������
			imageOutput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static byte[] createDimensionalCode(String value) {
		return createCode(Code39Encoder.class, value, false);
	}

	public static byte[] createCode(Class<?> clazz, String value, boolean checkDigit) {
		try {
			JBarcode localJBarcode = new JBarcode(getUnique(clazz), WidthCodedPainter.getInstance(),
					EAN13TextPainter.getInstance());
			localJBarcode.setPainter(WideRatioCodedPainter.getInstance());
			localJBarcode.setTextPainter(BaseLineTextPainter.getInstance());
			localJBarcode.setCheckDigit(checkDigit);
			localJBarcode.setShowCheckDigit(checkDigit);
			return getImageBytes(localJBarcode.createBarcode(value));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// ��ȡΨһ�����Ķ���
	private static BarcodeEncoder getUnique(Class<?> clazz) throws Exception {
		Constructor<?>[] constructors = clazz.getDeclaredConstructors();
		Constructor<?> privateConstructor = constructors[0];
		privateConstructor.setAccessible(true);
		return (BarcodeEncoder) privateConstructor.newInstance();
	}

	// ���ͼƬ�ֽ�������
	private static byte[] getImageBytes(BufferedImage paramBufferedImage) throws IOException {
		return ImageUtil.encode(paramBufferedImage, "jpeg", 96, 100);
	}
}
